﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.CarInsurance;
using CE.Company;
using CE.Mail;

public partial class car_result_detail : System.Web.UI.Page
{
    string _redirectUrl = "";

    protected void Page_Init(object sender, EventArgs e)
    {
        GetResultDetails();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            imgEmailQuote.Attributes.Add("onclick", "return confirm('Are you sure you want to send this quote?');");

            txtVehicleNo.Attributes.Add("onblur", "ShowValidationEffect('" + txtVehicleNo.ClientID + "','" + rfvVehicleNo.ClientID + "');");
            txtVehicleNo.Attributes.Add("onblur", "ShowValidationEffect('" + txtVehicleNo.ClientID + "','" + rfvVehicleNo.ClientID + "');");
        }
    }

    private void GetResultDetails()
    {
        string qs_carselected = "";

        if (Request.QueryString["crid"] != null)
        {
            qs_carselected = Request.QueryString["crid"].ToString();
        }

        if (qs_carselected != "" && Session[General.UserId] != null && Session[General.CarId] != null && Session[General.UserName] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);

                string CITempResultId = qs_carselected; // Session["CarSelected"].ToString();

                //dv.RowFilter = " CITempResultId in (" + CITempResultId.Remove(CITempResultId.Length - 1, 1) + ")";
                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        lblCarResultID.Text = CITempResultId;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            string _makemodel = "";
                            string _garagetype = "";
                            string _caryear = "";
                            string _ncd = "";
                            string _policystartdate = "";

                            Int64 _cecarid = 0;

                            if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
                            {
                                _cecarid = Convert.ToInt64(Session[General.CarId]);
                                Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                                Int64 _userId = 0;

                                if (Session[General.UserId] != null)
                                {
                                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                                }

                                CarDetail _cardetail = new CarDetail();
                                CarDetailDB _cardetaildb = new CarDetailDB();
                                _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

                                CarPolicy _carpolicy = new CarPolicy();
                                CarPolicyDB _carpolicydb = new CarPolicyDB();
                                _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

                                if (_cardetail != null)
                                {
                                    _makemodel = _cardetail.MakeModelDesc;
                                    _caryear = _cardetail.ManufactYear.ToString();
                                }

                                if (_carpolicy != null)
                                {
                                    _garagetype = "";
                                    _ncd = _carpolicy.NCDPercent.ToString();

                                    if (_ncd == "-1")
                                        _ncd = "0";

                                    _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
                                }


                                lblMakeModel.Text = _makemodel;
                                lblCarYear.Text = _caryear;
                                lblPolicyDate.Text = _policystartdate;
                                lblNCB.Text = _ncd + "%";
                                lblQuoteDate.Text = CE.Global.General.GetUTCDateTime().ToString("dd/MMM/yyyy");
                            }

                            //string convertno = General.GetRefNumber(_cecarid);                           
                            string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            //string convertno = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid);

                            if (_providercompanyid == "29")
                                lblRefNo.Text = "L" + General.GetRefNumber(_cecarid);
                            else if (_providercompanyid == "38")
                                lblRefNo.Text = "D" + General.GetRefNumber(_cecarid);

                            lblInsurer.Text = dtFiltered.Rows[iRows]["insurername"].ToString();

                            string companylogourl = dtFiltered.Rows[iRows]["CompanyLogoUrl"].ToString();

                            if (dtFiltered.Rows[iRows]["CompanyLogoUrl"].ToString().Substring(0, 1) == "~")
                            {
                                companylogourl = dtFiltered.Rows[iRows]["CompanyLogoUrl"].ToString().Remove(0, 1);
                            }

                            imgInsurer.ImageUrl = "http://www.comparexpress.com" + companylogourl;
                            imgInsurer.Width = 120;

                            //hlnkProvider.NavigateUrl = "provider_detail.aspx?pid=" + _providercompanyid;

                            //PlanName
                            lblPackage.Text = "<strong>" + dtFiltered.Rows[iRows]["providercovertypedesc"].ToString() + "</strong>";

                            //Premium
                            string annualprice = String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString()));
                            lblPrice.Text = annualprice;

                            //Deductible- Excess
                            String dec = dec = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["Excess"].ToString()));
                            lblExcess.Text = dec;

                            //Workshop??
                            lblWorkshopPlan.Text = dtFiltered.Rows[iRows]["PlanName"].ToString();

                            //Personal Accident (insured)
                            HtmlTableCell tcPA = new HtmlTableCell();
                            tcPA.Attributes.Add("class", "bg_grey_2 pad7px");
                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["PolicyHolder"].ToString()) == 0)
                            {
                                imgPA.Visible = true;
                                imgPA.ImageUrl = "http://www.comparexpress.com/images/icon/X.png";
                            }
                            else
                            {
                                lblPA.Text = String.Format("{0:#,0}", Convert.ToInt32(dtFiltered.Rows[iRows]["PolicyHolder"].ToString()));
                            }


                            //Personal Accident (each passenger)
                            HtmlTableCell tcPA2 = new HtmlTableCell();
                            tcPA2.Attributes.Add("class", "bg_grey_3 border1pxdotb_light pad7px");
                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["PassengerEach"].ToString()) == 0)
                            {
                                imgPAEP.Visible = true;
                                imgPAEP.ImageUrl = "http://www.comparexpress.com/images/icon/X.png";
                            }
                            else
                            {
                                lblPAEP.Text = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PassengerEach"].ToString()));
                            }

                            //MEdical Expense
                            lblMedExp.Text = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["MedicalExpense"].ToString()));

                            //Loss of Personal Effects

                            int _PersonnalEffectsLoss = Convert.ToInt32(dtFiltered.Rows[iRows]["PersonnalEffectsLoss"].ToString());
                            int _IsPersonnalEffectsLoss = 0;

                            if (dtFiltered.Rows[iRows]["IsPersonnalEffectsLoss"].ToString().Trim() != "" && dtFiltered.Rows[iRows]["IsPersonnalEffectsLoss"].ToString() != "0")
                                _IsPersonnalEffectsLoss = 1; // Convert.ToInt32(dtFiltered.Rows[iRows]["IsPersonnalEffectsLoss"].ToString());

                            string _PersonnalEffectsLossImageUrl = dtFiltered.Rows[iRows]["PersonnalEffectsLossUrl"].ToString();
                            if (_IsPersonnalEffectsLoss == 0)
                            {
                                imgLossPE.Visible = true;
                                //imgPersonnalEffectsLoss.ImageUrl = _PersonnalEffectsLossImageUrl;
                                lblLossPE.Visible = false;
                            }
                            else
                            {
                                imgLossPE.Visible = false;
                                lblLossPE.Visible = true;
                                lblLossPE.Text = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PersonnalEffectsLoss"].ToString()));
                            }

                            //Loss of Use

                            bool _IsCarReplace = false; // Convert.ToBoolean(Convert.ToSingle(dtFiltered.Rows[iRows]["IsCarReplacement"].ToString()));

                            if (dtFiltered.Rows[iRows]["IsCarReplacement"].ToString() != "" && dtFiltered.Rows[iRows]["IsCarReplacement"].ToString() != "0")
                                _IsCarReplace = true;

                            string _strCarReplace = Convert.ToString(dtFiltered.Rows[iRows]["CarReplacement"].ToString());

                            int _IsTranspoAllowance = 0; // Convert.ToInt32(dtFiltered.Rows[iRows]["isCashAllowance"].ToString());

                            if (dtFiltered.Rows[iRows]["isCashAllowance"].ToString() != "" && dtFiltered.Rows[iRows]["isCashAllowance"].ToString() != "0")
                                _IsTranspoAllowance = 1;

                            string _strTranspoAllowance = Convert.ToString(dtFiltered.Rows[iRows]["CashAllowance"].ToString());
                            string _strMaxTranspoAllowanceDays = Convert.ToString(dtFiltered.Rows[iRows]["MaxCashAllowanceDays"].ToString());

                            if (_IsCarReplace)
                            {
                                lblLossUse.Visible = true;
                                lblLossUse.Text = "Courtesy Car <br/>" + "max " + _strCarReplace + " day(s)";
                                imgLossUse.Visible = false;
                            }
                            else
                            {
                                if (_IsTranspoAllowance == 0)
                                {
                                    lblLossUse.Visible = true;
                                    lblLossUse.Text = "Transport Allowance<br/> S$" + _strTranspoAllowance + "/day <br/> max " + _strMaxTranspoAllowanceDays + " day(s)";

                                    imgLossUse.Visible = false;
                                }
                                else
                                {
                                    lblLossUse.Visible = false;
                                    lblLossUse.Text = "";

                                    imgLossUse.Visible = true;
                                    imgLossUse.ImageUrl = dtFiltered.Rows[iRows]["CarReplacementUrl"].ToString();

                                }
                            }
                            //string _citempresultid = dtFiltered.Rows[iRows]["CITempResultId"].ToString();


                        }

                    }
                }
            }
            else
            {
                Response.Redirect("car-result.aspx");
            }
        }
        else
        {
            Response.Redirect("car-result.aspx");
        }

    }

    protected void imgEmailQuote_Click(object sender, ImageClickEventArgs e)
    {
        string _emailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
        _emailList = Session[CE.Global.General.UserEmail].ToString();
        //_emailList += ";team@comparexpress.com";
        //string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString() + "/";
        string _currentDomainUrl = ""; // "http://www.comparexpress.com/";
        _title = "";

        _title = "CompareXpress.com (Ref No : " + lblRefNo.Text + ")";

        _message.Append("<table cellpadding='0' cellspacing='0' border='0' width='240' style='font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0 auto;'>");
        _message.Append("<tr><td style='border-bottom:1px solid #ccc;' align='center'><img src='http://www.comparexpress.com/images/nav/logo_comparexpress.png' alt='' height='78' /><br/><br/>");
        _message.Append("Thank you for choosing CompareXpress.com <br/><strong>Here is your Quote Details </strong><br /><br/></td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><br /><table cellspacing='0' cellpadding='2' width='100%' border='0'>");

        _message.Append("<tr><td valign='top'>Quote Ref Number</td>");
        _message.Append("<td valign='top'><strong><u>" + lblRefNo.Text + "</u></strong></td></tr>");

        _message.Append("<tr><td valign='top'>Car Make & Model</td>");
        _message.Append("<td valign='top'><strong>" + lblMakeModel.Text + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>Car Model year</td>");
        _message.Append("<td valign='top'><strong>" + lblCarYear.Text + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>Cover Commencement Date</td>");
        _message.Append("<td valign='top'><strong>" + lblPolicyDate.Text + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>NCD</td>");
        _message.Append("<td valign='top'><strong>" + lblNCB.Text + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>Quote Date</td>");
        _message.Append("<td valign='top'><strong>" + lblQuoteDate.Text + "</strong></td></tr>");

        _message.Append("</table><br /></td></tr><tr><td width='300'><br />");

        _message.Append("<table width='100%' border='0' cellpadding='5' cellspacing='0'  class='table_details'>");

        _message.Append("<tr><td width='45%'></td>");
        _message.Append("<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'>");
        _message.Append("<img src='" + imgInsurer.ImageUrl + "'  width='120px' /></td></tr>");

        _message.Append("<tr><td><strong>Insurer</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5; color:black;' ><strong>" + lblInsurer.Text + "</strong></td></tr>");

        _message.Append("<tr><td></td>");
        _message.Append("<td align='center' style='background:#d5d5d5;'>" + lblPackage.Text + "</td></tr>");

        _message.Append("<tr><td align='left' style='background:#d5d5d5' ><strong>Annual Premium</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5; color:black; font-size:16px;'><strong>" + lblPrice.Text + "</strong></td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Excess</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + lblExcess.Text + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Workshop Plan</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + lblWorkshopPlan.Text + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Personal Accident (insured)</strong></td>");
        _message.Append("<td align='center' style='background:#c5c5c5;'>");

        if (imgPA.Visible)
            _message.Append("<img src='" + _currentDomainUrl + imgPA.ImageUrl + "' /></td></tr>");
        else
            _message.Append(lblPA.Text + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Personal Accident (each passenger)</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (imgPAEP.Visible)
            _message.Append("<img src='" + _currentDomainUrl + imgPAEP.ImageUrl + "' /></td></tr>");
        else
            _message.Append(lblPAEP.Text + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Medical Expense</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + lblMedExp.Text + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Loss of Personal Effects</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (imgLossPE.Visible)
            _message.Append("<img src='" + _currentDomainUrl + imgLossPE.ImageUrl + "' /></td></tr>");
        else
            _message.Append(lblLossPE.Text + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Loss of Use (benefit)</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        if (imgLossUse.Visible)
            _message.Append("<img src='" + _currentDomainUrl + imgLossUse.ImageUrl + "' /></td></tr>");
        else
            _message.Append(lblLossUse.Text + "</td></tr>");


        _message.Append("</table><br /><br />");


        _message.Append("<strong>Remarks</strong><br />");
        _message.Append("1 - The quotation valid for 7 days and subject to change without notice according to policy of company.<br />");
        _message.Append("2- Premium and coverage are subject to underwriting criteria of insurance company. <br />");
        _message.Append("</td></tr><tr><td id='email_footer'></td>");
        _message.Append("</tr></table><br /><br /><hr />This Quote is subject to the insurer's final confirmation and coverage is only effective when the insurer has accepted the risk.<br /><br />");
        _message.Append("<i>This is a computer-generated email. Please do not reply to this email.</i><hr />");

        string bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.CX_CARBCC");
        MyMailManager.SendCRMMessage(_emailList, "", bccemail, _title, _message.ToString());

        Response.Redirect("email-confirm.aspx?type=email&resultid=" + lblCarResultID.Text);
    }

    protected void imgbtnCallMe_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.CarId] != null)
            {
                string _message = "";
                string _title = "";
                string _ec = "";
                string _calltype = "1";
                string _makemodel = "";

                _message = "Customer Name: " + Session[General.UserName].ToString();
                _title = "Call Me request by " + Session[General.UserName].ToString() + " for Liberty Insurance";

                Int64 _result = 0;
                ContactUser _contactuser = new ContactUser();
                ContactUserDB _contactuserdb = new ContactUserDB();

                _contactuser.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _contactuser.ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                _contactuser.ProviderCompanyId = 29;
                _ec = "1029";
                _contactuser.InsuranceType = "CI";
                _contactuser.FullName = Session[General.UserName].ToString();
                _contactuser.ContactNo = Session[General.UserPhoneNo].ToString();
                _contactuser.CallTime = 4;
                _contactuser.AgentId = 0;
                _contactuser.Status = true;
                _contactuser.Info1 = _calltype;
                _contactuser.Info2 = txtVehicleNo.Text;
                _contactuser.Info3 = "";

                _result = _contactuserdb.Insert(_contactuser);
                if (_result > 0)
                {
                    CXAgent _cxagent = new CXAgent();
                    CXAgentDB _cxagentdb = new CXAgentDB();
                    Int64 _ProductId = 0;
                    Int64 _AgentId = 0;
                    Int64 _CEID = Convert.ToInt64(Session[General.UserId].ToString());
                    string _AgentName = "";
                    string _AgentEmail = "";
                    string _CCEmail = "";
                    string _BCCEmail = "";
                    DataTable _dtCXAgent = _cxagentdb.GetCXAgentList(_CEID, "CM", 0);
                    if (_dtCXAgent != null && _dtCXAgent.Rows.Count > 0)
                    {
                        _AgentId = Convert.ToInt64(_dtCXAgent.Rows[0]["AgentId"].ToString());
                        _AgentName = _dtCXAgent.Rows[0]["AgentName"].ToString();
                        _AgentEmail = _dtCXAgent.Rows[0]["Email"].ToString();

                        _ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                        _contactuserdb.Update(_CEID, _AgentId, _contactuser.ProviderCompanyId, "CM", _ProductId);

                        _message += "<br/><br/>Make/Model : " + lblCarYear.Text + " " + lblMakeModel.Text;
                        _message += "<br/><br/><b>Insurer : <span style='color:#f00'> Liberty Insurance";
                        _message += "</span></b><br/><br/>Contact No : " + Session[General.UserPhoneNo].ToString(); ;
                        _message += "<br/><br/>Call Time : Anytime ";
                        _message += "<br/><br/>Agent Name : " + _AgentName;
                        //string _emailList = ConfigurationManager.AppSettings["CICallMeMessageReceiver"].ToString();
                        //MyMailManager.SendCRMMessage(_emailList, _title, _message);
                        _CCEmail = ConfigurationManager.AppSettings["Mobile.CC_CICallMeMessageReceiver"].ToString();
                        _BCCEmail = ConfigurationManager.AppSettings["Mobile.BCC_CICallMeMessageReceiver"].ToString();
                        MyMailManager.SendCallMeMessage(_AgentEmail, _CCEmail, _BCCEmail, _title, _message);
                        Response.Redirect("usermessage.aspx");
                    }
                }

            }
        }
    }

}
